package leetcode;

/**
 * Created by Ghost on 2014/10/9 0009.
 */
public class Linked_List_Cycle_II {
    public ListNode detectCycle(ListNode head) {
        if(head==null)
            return null;
        ListNode fast = head;
        ListNode slow = head;
        while(fast!=null){
            slow = slow.next;
            fast = fast.next;
            if(fast!=null)
                fast = fast.next;
            if(slow==fast && slow!=null){
                break;
            }
        }
        if(slow == fast && slow!=null){
            slow = head;
            while(slow!=fast){
                slow = slow.next;
                fast = fast.next;
            }
            return slow;
        }
        else
            return null;
    }
    public static void main(String[] args){
        ListNode head = new ListNode(1);
//        head.next = new ListNode(2);
//        head.next.next = new ListNode(3);
//        head.next.next.next = new ListNode(4);
//        head.next.next.next.next = new ListNode(5);
//        head.next.next.next.next.next = head.next.next.next;
        Linked_List_Cycle_II linked_list_cycle_ii = new Linked_List_Cycle_II();
        ListNode c = linked_list_cycle_ii.detectCycle(head);
        System.out.println(c);
    }
}
